<template>
  <div style="width: 100vw;height: 100vh;display: flex;flex-direction: column;overflow: hidden;">
    <div style="height: 10vh; background-color: #f5f5f5; min-height: 60px; flex-shrink: 0;">
      <el-row :gutter="10">
        <el-col :span="1">
          <img src="../../../public/imgs/login/leaf.png" style="height: 40px; padding-top: 13px; padding-left: 16px;">
        </el-col>
        <el-col :span="15">
          <span style="font-size: 25px; color: #35984b; padding-left: 40px; line-height: 10vh;font-weight: bold;">垃圾分类管理项目后台</span>
        </el-col>
      </el-row>
    </div>

    <div style="display: flex; height: 90vh;">
      <!-- 左侧菜单栏 -->
      <div style="width: 228px">
        <el-menu
            background-color="#35984b"
            style="width: 100%; height: 100vh; border: none;"
            text-color="#fff"
            active-text-color="#fff"
            router
            :collapse-transition="true"
        >
          <el-menu-item index="/adminNotice">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Promotion /></el-icon>
              <span class="left-menu-item">资讯管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminGarbage">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><DeleteFilled /></el-icon>
              <span class="left-menu-item">垃圾管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminUser">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><UserFilled /></el-icon>
              <span class="left-menu-item">用户管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminPut">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><CircleCheckFilled /></el-icon>
              <span class="left-menu-item">投放管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/admin">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Avatar /></el-icon>
              <span class="left-menu-item">个人中心</span>
            </template>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧顶部条与主体内容（可变区域）-->
      <div style="width: calc(100% - 228px)">
        <el-header style="height: 80px; background-color: #fff; padding-top: 22px;">
          <el-row>
            <!-- 登录人姓名和退出登录 -->
            <el-col :span="24">
              <div style="display: flex; justify-content: space-between; align-items: center; height: 100%; padding:0 20px;">
                <!-- 面包屑导航 -->
                <el-breadcrumb separator="/" style="margin-left: 10px;">
                  <el-breadcrumb-item
                      v-for="item in breadcrumb"
                      style="font-size: 16px; font-weight: 500;"
                  >
                    | {{ item }}
                  </el-breadcrumb-item>
                </el-breadcrumb>

                <!-- 用户信息 -->
                <div>
                  <el-dropdown trigger="click">
                    <div style="display: flex; align-items: center; cursor: pointer; padding: 8px 12px; border-radius: 4px;">
                      <el-icon><User /></el-icon>
                      <span style="font-size: 16px; font-weight: 500; color: #606266; margin-left: 8px; margin-right: 8px;">{{ user.username }}</span>
                      <el-icon><ArrowDown /></el-icon>
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu style="--el-dropdown-menuItem-hover-fill: #f6f6f6; --el-dropdown-menuItem-hover-color: #008800;">
                        <el-dropdown-item @click="toAdmin">
                          <el-icon><Avatar /></el-icon>个人中心
                        </el-dropdown-item>
                        <el-dropdown-item @click="logout" divided>
                          <el-icon><SwitchButton /></el-icon>退出登录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-header>
        <!-- 右侧主体内容 -->
        <el-main style=" padding: 0; height: calc(100vh - 10vh - 100px); overflow-y: auto;">
          <!-- 新建用户弹窗 -->
          <el-dialog
              :title="dialogTitle"
              style="width:600px;padding:40px;"
              v-model="dialogVisible"
              :before-close="handleClose"
          >
            <el-form label-position="top" label-width="80">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="用户名">
                    <el-input placeholder="请输入用户名" v-model="saveUserForm.username"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号">
                    <el-input placeholder="请输入手机号" v-model="saveUserForm.phone"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="性别">
                    <el-radio-group v-model="saveUserForm.gender">
                      <el-radio border label="男" value="男"></el-radio>
                      <el-radio border label="女" value="女"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份">
                    <el-radio-group v-model="saveUserForm.role">
                      <el-radio border label="user" value="user"></el-radio>
                      <el-radio border label="admin" value="admin"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <el-button type="info" @click="handleClose">取消</el-button>
              <el-button type="success" @click="saveUser">保存</el-button>
            </template>
          </el-dialog>
          <!-- 用户搜索卡片 -->
          <el-card style="margin: 10px;height: 70px;">
            <el-form :inline="true">
              <el-form-item label="用户名" style="width: 270px;">
                <el-input placeholder="请输入用户名" v-model="searchUserForm.username"></el-input>
              </el-form-item>
              <el-form-item label="用户身份" style="width: 290px;">
                <el-select placeholder="请选择用户身份" v-model="searchUserForm.role">
                  <el-option label="user" value="user"></el-option>
                  <el-option label="admin" value="admin"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="info" @click="resetSearch">重置</el-button>
                <el-button type="success" @click="loadUser">搜索</el-button>
              </el-form-item>
              <el-form-item style="float: right; margin-bottom: 20px;">
                <el-button type="success" style="float:right;"
                           @click="beforeAddUser">新建用户</el-button>
              </el-form-item>
            </el-form>

          </el-card>
          <!-- 用户表格卡片 -->
          <el-card style="margin: 10px; display: flex; flex-direction: column; min-height: calc(100% - 10vh - 100px);">
            <el-table :data="pagedUserArr" style="flex: 1;">
              <el-table-column type="index" label="序号" width="80" align="center">
                <template #default="scope">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="username" label="用户名" align="center"></el-table-column>
              <el-table-column prop="gender" label="性别" align="center"></el-table-column>
              <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
              <el-table-column prop="role" label="身份" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button type="primary" link @click="resetPassword(scope.row.id)">密码重置</el-button>
                  <el-button type="success" link @click="editUser(scope.row.id)">编辑</el-button>
                  <el-button type="danger" link @click="deleteUser(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div style="padding: 20px 0; text-align: center;">
              <el-pagination
                  layout="prev, pager, next"
                  :total="userArr.length"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="handlePageChange"
              />
            </div>
          </el-card>
        </el-main>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  Message,
  Delete,
  User,
  Avatar,
  ArrowDown,
  SwitchButton
} from '@element-plus/icons-vue'
import axios from "axios";
import qs from "qs";

// 获取当前登录用户的信息
const user = ref(getUser());

const toAdmin = () => {
  router.push('/admin');
}
// 退出登录方法
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    localStorage.removeItem('user');
    window.location.href = '/login';
    user.value = '';
  }).catch(()=>{

  })
}
// 更新面包屑映射
let map = {
  '/adminNotice': ['资讯管理'],
  '/adminGarbage': ['垃圾管理'],
  '/admin': ['个人中心'],
  '/adminUser': ['用户管理'],
  '/adminPut': ['投放管理'],
}
const breadcrumb = ref([]);
const route = useRoute();
const router = useRouter();
onMounted(() => {
  updateBreadcrumb(route);
})
// 定义更新面包屑导航值的方法
const updateBreadcrumb = (route) => {
  const path = route.path;
  breadcrumb.value = map[path] || [];
}
// 监听路由变化，更新面包屑
router.beforeEach((to, from, next) => {
  updateBreadcrumb(to);
  next();
})

//定义变量用来控制弹窗是否出现
const dialogVisible = ref(false);
//定义对象用来收集用户保存表单的数据
const saveUserForm = ref({
  username:'',
  phone:'',
  gender:'',
  role:''
});
//定义保存用户的方法
const saveUser = ()=>{
  console.log(saveUserForm.value);
  let data = qs.stringify(saveUserForm.value);
  axios.post('http://localhost:8080/v1/user/save',data)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('保存成功!');
          dialogVisible.value = false;
          saveUserForm.value = {};
          loadUser();
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
const isEdit = ref(false);
//定义处理弹窗关闭的方法
const handleClose = () => {
  if (isEdit.value) {
    // 直接关闭
    saveUserForm.value = {};
    dialogVisible.value = false;
  } else {
    // 如果是添加状态才提示
    ElMessageBox.confirm('确定要放弃新建用户吗？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      saveUserForm.value = {};
      dialogVisible.value = false;
    }).catch(() => {});
  }
};
//定义对象用来保存用户搜索条件
const searchUserForm = ref({username:'', role:''});
const userArr  = ref([]);
//定义加载用户数据的方法
const loadUser = () => {
  let data = qs.stringify(searchUserForm.value);
  axios.get('http://localhost:8080/v1/user/select?'+data).then((response)=>{
    if(response.data.code == 2000){
      userArr.value = response.data.data;
      currentPage.value = 1; // 搜索后重置到第一页
    }else{
      ElMessage.error(response.data.msg);
    }
  })
};
onMounted(()=>{
  loadUser();
})
//定义取消搜索的方法
const resetSearch = ()=>{
  searchUserForm.value = {};
  loadUser();
}
//定义变量用来维护弹窗标题
const dialogTitle = ref('新增用户');
//定义点击新增用户按钮时调用的方法:处理新增用户时弹窗的标题
const beforeAddUser = ()=>{
  dialogTitle.value = '新增用户';
  dialogVisible.value = true;
}
//定义点击编辑按钮时调用的方法
const editUser = (id)=>{
  dialogTitle.value = '编辑用户';
  isEdit.value = true;
  dialogVisible.value = true;
  //获取当前待编辑的用户数据,回显在弹窗中
  axios.get('http://localhost:8080/v1/user/select?id='+id).then((response)=>{
    if(response.data.code == 2000){
      //后端返回的数据类型是List<UserVO>,前端以数组类型接收,所以需要data[0]取数组的第一个元素才行
      saveUserForm.value = response.data.data[0];
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
//定义重置密码的方法
//restful风格:以斜杠的方式拼接传参,后端需要@PathVariable注解来接收参数值
const resetPassword = (userId)=>{
  axios.post('http://localhost:8080/v1/user/update/password/'+userId)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('密码重置成功!');
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
// 定义删除用户的方法
const deleteUser = (userId) => {
  ElMessageBox.confirm('确定删除该用户吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    axios.post('http://localhost:8080/v1/user/delete/' + userId)
        .then((response) => {
          if (response.data.code == 2000) {
            ElMessage.success('删除成功!');
            loadUser(); // 删除成功后,需要重新加载用户列表数据!
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch((error) => {
          ElMessage.error('删除用户时发生错误');
          console.error(error);
        });
  }).catch(() => {
    // 用户点击取消，不执行任何操作
  });
}
// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(7);

// 计算属性：返回当前页的数据
const pagedUserArr = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return userArr.value.slice(start, end);
});

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};

</script>

<style scoped>
.left-menu-item {
  font-size: 18px;
  padding-left: 12px;
}

.left-menu-collapse-item {
  font-size: 17px;
  border: none;
  height: 40px;
}

/* 自定义滚动条样式 */
.el-main::-webkit-scrollbar {
  width: 8px;
}

.el-main::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.el-main::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.el-pagination {
  justify-content: center;}

</style>